import os

from django.contrib.auth.models import AbstractUser
from django.db import models

# Create your models here.
from django.db.models.signals import post_delete
from django.dispatch import receiver

from ex_blog.DjangoUeditor.models import UEditorField
from iblog import settings
from iblog.settings import MEDIA_ROOT

"""
title category tags body user views tui  created_time
文章标题 外键，关联文章分类表 	多对多，关联标签列表 文章内容 外键，文章作者关联用户模型，系统自带的 
文章浏览数，正的整数，不能为负 外键，关联推荐位表 文章发布时间
"""


class Author(AbstractUser):
    author_name = models.CharField(max_length=64, verbose_name='作者名字')

    class Meta:
        db_table = 'author'
        verbose_name = '作者'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username


class Article(models.Model):
    title = models.CharField(max_length=128, verbose_name='文章标题')
    category = models.ForeignKey(
        to='Category',
        db_constraint=False,
        related_name='articles',
        on_delete=models.DO_NOTHING,
        verbose_name='文章分类',
    )
    tag = models.ManyToManyField(
        to='Tag',
        db_constraint=False,
        related_name='articles'
    )
    # body = models.TextField()
    body = UEditorField('内容', width=800, height=500,
                        toolbars='full', imagePath='upimg/', filePath='upfile/',
                        upload_settings={'imageMaxSize': 1204000},
                        settings={}, command=None, blank=True
                        )
    user = models.ForeignKey(
        to='Author',
        db_constraint=False,
        related_name='articles',
        on_delete=models.DO_NOTHING,
        verbose_name='作者',
    )
    # views = models.PositiveIntegerField(verbose_name='文章浏览数')
    views = models.PositiveIntegerField(default=0, editable=False, verbose_name='文章浏览数')
    tui = models.ForeignKey(
        to='Tui',
        db_constraint=False,
        related_name='articles',
        on_delete=models.DO_NOTHING,
    )
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='写作时间')
    # 文章更新时间。参数 auto_now=True 指定每次数据更新时自动写入当前时间
    updated = models.DateTimeField(auto_now=True,verbose_name='最近更新时间')

    class Meta:
        db_table = 'article'
        verbose_name = '文章'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title


# 分类表
class Category(models.Model):
    name = models.CharField(max_length=32, verbose_name='分类名')

    class Meta:
        db_table = 'category'
        verbose_name = '分类表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


# 标签
class Tag(models.Model):
    name = models.CharField(max_length=32, verbose_name='标签名')

    class Meta:
        db_table = 'tag'
        verbose_name = '标签'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


# 推荐位
class Tui(models.Model):
    name = models.CharField(max_length=32, verbose_name='推荐位')

    class Meta:
        db_table = 'tui'
        verbose_name = '推荐位'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


# 轮播图
# def upload_to_banner(instance, filename):
#     return '/'.join(
#         [MEDIA_ROOT, 'Banner', filename])

class Banner(models.Model):
    text_info = models.CharField(max_length=100, verbose_name='标题')
    img = models.ImageField(verbose_name='图片类型  (轮播图)', upload_to='Banner')
    link_url = models.URLField(verbose_name='图片链接的URL')
    is_active = models.BooleanField(verbose_name='激活状态')

    class Meta:
        db_table = 'banner'
        verbose_name = '轮播图'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.text_info


# 重写删除文件功能，项目删除的时候，文件也跟随删除
@receiver(post_delete, sender=Banner)
def delete_upload_files(sender, instance, **kwargs):
    # item_file是Item的属性
    print('尼玛')
    files = getattr(instance, 'img', '')
    if not files:
        print('怎么没有文件')
        return
    fname = os.path.join(settings.MEDIA_ROOT, files.name)
    print('卧槽', fname)
    if os.path.isfile(fname):
        os.remove(fname)


# 图片库
class Image(models.Model):
    img_title = models.CharField(max_length=100, verbose_name='标题')
    img = models.ImageField(verbose_name='图片类型（图片库）', upload_to='img')
    # link_url = models.URLField(verbose_name='图片的URL')
    is_active = models.BooleanField(verbose_name='激活状态')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')

    class Meta:
        db_table = 'image'
        verbose_name = '图片库'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.img_title


# 重写删除文件功能，项目删除的时候，文件也跟随删除
@receiver(post_delete, sender=Image)
def delete_upload_files(sender, instance, **kwargs):
    files = getattr(instance, 'img', '')
    if not files:
        return
    fname = os.path.join(settings.MEDIA_ROOT, files.name)
    if os.path.isfile(fname):
        os.remove(fname)


# 友链
class Link(models.Model):
    name = models.CharField(max_length=70, verbose_name='友情链接名称')
    link_url = models.URLField(verbose_name='友情链接的URL')

    class Meta:
        db_table = 'link'
        verbose_name = '友情链接'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


# 评论
class BlogComment(models.Model):
    user_name = models.CharField('评论者名字', max_length=100)
    user_email = models.EmailField('评论者邮箱', max_length=255)
    body = models.TextField('评论内容')
    created_time = models.DateTimeField('评论发表时间', auto_now_add=True)
    article = models.ForeignKey(to='Article', verbose_name='评论所属文章', on_delete=models.CASCADE)

    def __str__(self):
        return self.body[:20]

    class Meta:
        db_table = 'blogComment'
        verbose_name = '博客评论'
        verbose_name_plural = verbose_name


# 验证码
class EmailVerifyCode(models.Model):
    code = models.CharField(max_length=20, verbose_name='验证码')
    email = models.EmailField(max_length=200, verbose_name='验证码邮箱')
    send_type = models.IntegerField(choices=((1, 'register'), (2, 'forget'), (3, 'change')),
                                    verbose_name='验证码类型')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')

    def __str__(self):
        return self.code

    class Meta:
        db_table = 'emailverifycode'
        verbose_name = '邮箱验证码信息'
        verbose_name_plural = verbose_name
